package com.hainatong.shiphelper.module.workermgr.viewmodel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.blankj.utilcode.util.StringUtils;
import com.hainatong.shiphelper.Constants;
import com.hainatong.shiphelper.api.ApiResult;
import com.hainatong.shiphelper.api.ApiService;
import com.hainatong.shiphelper.api.HttpResult;
import com.hainatong.shiphelper.api.VMObserver;
import com.hainatong.shiphelper.mainhome.entity.WhereComBean;
import com.hainatong.shiphelper.module.cert.entity.CertBean;
import com.hainatong.shiphelper.module.warehouse.entity.ShipOrgBean;
import com.hainatong.shiphelper.module.workermgr.entity.WorkerBean;
import com.hainatong.shiphelper.utils.GsonUtil;
import com.hainatong.mvvmbase.base.BaseViewModel;
import com.hainatong.mvvmbase.base.LiveResult;
import com.hainatong.mvvmbase.base.PageLiveResult;
import com.hainatong.mvvmbase.http.RxSchedulersUtils;

import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.disposables.Disposable;

public class OrgUserViewModel extends BaseViewModel
{
    private int page;

    private boolean isRefresh = false;

    private boolean isHasNextPage = false;

    private String keyWord;

    private String roleId;


    public OrgUserViewModel(@NonNull Application application)
    {
        super(application);
    }

    private MutableLiveData<LiveResult<List<ShipOrgBean>>> orgUserResult = new MutableLiveData<>();

    public MutableLiveData<LiveResult<List<ShipOrgBean>>> getOrgUserResult()
    {
        return orgUserResult;
    }

    /**
     *  查询  人员 组织
     * @param lan
     */
    public void queryOrgUserListByLan(String lan)
    {
        ApiService.Builder.getChanBoServer()
                .getOrgUsers(lan)
                .compose( RxSchedulersUtils.Obs_io_main() )
                .subscribe(new VMObserver<ApiResult<List<ShipOrgBean>>>() {
                    @Override
                    public void onStart(Disposable d)
                    {
                        addDisposable( d );
                    }

                    @Override
                    public void onError(int code, String errorMsg)
                    {
                        getOrgUserResult().postValue( new LiveResult<>( false ,errorMsg ) );
                    }

                    @Override
                    public void onSuccess(ApiResult<List<ShipOrgBean>> result)
                    {
                        if( result.isOk() )
                        {
                            getOrgUserResult().postValue( new LiveResult<>( true ,result.getData() ) );
                        }
                        else
                        {
                            getOrgUserResult().postValue( new LiveResult<>( false ,result.getMessage() ) );
                        }
                    }
                });
    }


    private MutableLiveData<PageLiveResult<List<WorkerBean>>>  userListResult = new MutableLiveData<>();

    public MutableLiveData<PageLiveResult<List<WorkerBean>>> getUserListResult()
    {
        return userListResult;
    }

    private void queryUsersByParam(int mPage, String roleId, String keyName)
    {
        Map<String,Object> param = new HashMap<String,Object>();
        param.put(Constants.Key.PAGE,  String.valueOf( mPage ) );
        param.put( Constants.Key.ROWS, Constants.DEF_PAGE_SIZE);
        List<WhereComBean> whereList = new ArrayList<>();
        if( !StringUtils.isEmpty( roleId ))
        {
            whereList.add( new WhereComBean( "Role_Id", roleId ) );
        }
        if( !StringUtils.isEmpty( keyName ) )
        {
            whereList.add( new WhereComBean( "UserTrueName", keyName) );
        }
        param.put( "wheres", GsonUtil.obj2json( whereList ));

        ApiService.Builder.getChanBoServer()
                          .getUsersByParams( param )
                          .compose( RxSchedulersUtils.Obs_io_main() )
                          .subscribe(new VMObserver<HttpResult<List<WorkerBean>>>()
                          {
                              @Override
                              public void onStart(Disposable d)
                              {
                                 addDisposable( d );
                              }

                              @Override
                              public void onError(int code, String errorMsg)
                              {
                                  PageLiveResult<List<WorkerBean>> errorResult = new PageLiveResult<>();
                                  errorResult.setSuccess(false);
                                  errorResult.setRefresh(isRefresh);
                                  errorResult.setMsg(errorMsg);
                                  if( !isRefresh )
                                  {
                                      errorResult.setLoadMoreEmpty(true);
                                  }
                                  getUserListResult().postValue( errorResult );
                              }

                              @Override
                              public void onSuccess(HttpResult<List<WorkerBean>> result)
                              {
                                  if( result.isOk() )
                                  {
                                      PageLiveResult<List<WorkerBean>> listResult = new PageLiveResult<>();
                                      listResult.setSuccess(true);
                                      listResult.setRefresh(isRefresh);
                                      if( result.getRows() != null && !result.getRows().isEmpty() )
                                      {
                                          listResult.setData( result.getRows() );
                                          if( result.getRows().size() < Constants.DEF_PAGE_SIZE )
                                          {
                                              isHasNextPage = false;
                                          }
                                          else
                                          {
                                              isHasNextPage = true;
                                              page = page + 1;
                                          }
                                      }
                                      getUserListResult().postValue(listResult);
                                  }
                                  else
                                  {
                                      PageLiveResult<List<WorkerBean>> failResult = new PageLiveResult<>();
                                      failResult.setSuccess(false);
                                      failResult.setRefresh(isRefresh);
                                      failResult.setMsg(result.getMsg());
                                      if( !isRefresh )
                                      {
                                          failResult.setLoadMoreEmpty(true);
                                      }
                                      getUserListResult().postValue(failResult);
                                  }
                              }
                          });

    }

    public void queryUserByRoleId( String roleId ,String keyName )
    {
        this.page = 1;
        this.isRefresh = true;
        this.isHasNextPage = true;
        this.roleId = roleId;
        this.keyWord = keyName;
        queryUsersByParam(this.page , this.roleId , keyName );
    }

    public void tryRefreshUser()
    {
        queryUserByRoleId(this.roleId,this.keyWord);
    }

    public void loadMoreUser()
    {
        if( isHasNextPage )
        {
            this.isRefresh = false;
            queryUsersByParam(this.page,this.roleId,this.keyWord);
        }
        else
        {
            PageLiveResult<List<WorkerBean>> emptyResult = new PageLiveResult<>();
            emptyResult.setSuccess(false);
            emptyResult.setLoadMoreEmpty(true);
            emptyResult.setRefresh(false);
            getUserListResult().postValue(emptyResult);
        }
    }



    private MutableLiveData<LiveResult<List<CertBean>>> certListResult = new MutableLiveData<>();

    public MutableLiveData<LiveResult<List<CertBean>>> getCertListResult()
    {
        return certListResult;
    }

    /**
     *  查询 证书 列表
     */
    public void queryUserCertByUuid(String userUuid)
    {
        //{"wheres":"[{}]","rows":"50","page":"1"}
        Map<String,Object> param = new HashMap<String,Object>();
        param.put(Constants.Key.PAGE, "1");
        param.put( Constants.Key.ROWS, "100");
        // 查询 参数
        List<WhereComBean> whereList = new ArrayList<>();
        whereList.add( new WhereComBean( "userid", userUuid) );
        //whereList.add( new WhereComBean( "dict_level", "1" ) );
        param.put( "wheres", GsonUtil.obj2json( whereList ));

        ApiService.Builder.getChanBoServer()
                .getUserCertList(param)
                .compose( RxSchedulersUtils.Obs_io_main() )
                .subscribe(new VMObserver<HttpResult<List<CertBean>>>()
                {
                    @Override
                    public void onStart(Disposable d)
                    {
                        addDisposable( d );
                    }

                    @Override
                    public void onError(int code, String errorMsg)
                    {
                        getCertListResult().postValue( new LiveResult<>( false ,errorMsg ) );
                    }

                    @Override
                    public void onSuccess(HttpResult<List<CertBean>> result)
                    {
                        if( result.isOk() )
                        {
                            getCertListResult().postValue( new LiveResult<>( true ,result.getRows() ) );
                        }
                        else
                        {
                            getCertListResult().postValue( new LiveResult<>( false ,result.getMsg() ) );
                        }
                    }
                });

    }



}
